package email;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import database.Database;

public class Email {

	private static final String host_1 = "smtp.sina.com";
	private static final String host_2 = "pop3.sina.com";
	private static final String home_address = "zzzbelle@sina.com";
	private static final String password = "yw123456";
	
	public static void sendMail(String target_address) {
		Properties props = System.getProperties();
		props.put("mail.smtp.host", host_1);
		props.put("mail.smtp.auth", "true");
		Session session = Session.getDefaultInstance(props, new Authenticator(){
			@Override
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(home_address, password);
			}
		});
		
		try {
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(home_address));
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(target_address));
			message.setSubject("this weekend homework");
			message.setText("Do you think it is hard? Please return with yes or no.");
			Transport.send(message);

		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public static ArrayList<EmailContent> ReceiveMail() throws Exception {
		
		ArrayList<EmailContent> results = new ArrayList<>();
		Properties props = new Properties();
		props.setProperty("mail.store.protocol", "pop3");
		props.setProperty("mail.pop3.host", host_2);
		
		Session session = Session.getInstance(props);
		Store store = session.getStore("pop3");
		
		store.connect(host_2, home_address, password);
		Folder folder = store.getFolder("inbox");
		
		folder.open(Folder.READ_WRITE);
		
		Message[] messages = folder.getMessages();
		
		for (int i = 0; i < messages.length; i++) {
			
			MimeMessage msg = (MimeMessage) messages[i];
			InternetAddress address = (InternetAddress) msg.getFrom()[0];
			String subject = MimeUtility.decodeText(msg.getSubject());
			
			StringBuffer content = new StringBuffer();
			getMailTextContent(msg, content);
			
			results.add(new EmailContent(address.getAddress(), subject, content.toString()));
			
		}
		folder.close(true);
		store.close();

		return results;
	}	
	
	private static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException { 
        //如果是文本类型的附件，通过getContent方法可以取到文本内容，但这不是我们需要的结果，所以在这里要做判断 
        boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;  
        if (part.isMimeType("text/*") && !isContainTextAttach) { 
            content.append(part.getContent().toString()); 
        } else if (part.isMimeType("message/rfc822")) {  
            getMailTextContent((Part)part.getContent(),content); 
        } else if (part.isMimeType("multipart/*")) { 
            Multipart multipart = (Multipart) part.getContent(); 
            int partCount = multipart.getCount(); 
            for (int i = 0; i < partCount; i++) { 
                BodyPart bodyPart = multipart.getBodyPart(i); 
                getMailTextContent(bodyPart,content); 
            } 
        } 
    } 
	
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub

		
		Database test = new Database();
		test.Connect();
		ArrayList<String> addresses = test.SelectAll();
		test.Close();
		
		/*
		//发邮件
		for (String s: addresses) {
			Email.sendMail(s);
		}
		*/
		
		
		//收邮件
		ArrayList<EmailContent> results = Email.ReceiveMail();
		for (EmailContent c : results) {
			
			if (c.content.toLowerCase().contains("yes")) {
				System.out.println(c.address + ":" + "it is hard!");
			}
			else if (c.content.toLowerCase().contains("no"))
			{
				System.out.println(c.address + ":" + "it is easy!");
			}
			
		}
		
	}
}

